package edu.pku.sei.mte.compositetrans.flow;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class ForkNode extends FlowNode {

	private FlowController flowController = null;
	private List<FlowNode> nextNodes = null;
	
	@Override
	public FlowNode getNext() {
		if(nextNodes.isEmpty())
			return FlowController.WRONG_OF_FLOW;
		for(int i = 1; i < nextNodes.size(); i++)
			flowController.addNewPath(nextNodes.get(i));
		return nextNodes.get(0);
	}
	
	public List<FlowNode> getNextNodes() {
		if(nextNodes == null)
			nextNodes = new ArrayList<FlowNode>();
		return nextNodes;
	}

	public void setFlowController(FlowController flowController) {
		this.flowController = flowController;
	}

	@Override
	public void load(Element e, Map<Integer, FlowNode> FlowNodesMap) {
		NodeList nl = e.getChildNodes();
		for(int i=0;i<nl.getLength();i++){
			Node n = nl.item(i);
			if(n.getNodeType()!=Node.ELEMENT_NODE)
				continue;
			Element ee = (Element) n;
			if(ee.getTagName().equals("post")){
				FlowNode fn = FlowNodesMap.get(Integer.parseInt(ee.getAttribute("nid")));
				getNextNodes().add(fn);
				if (fn instanceof JoinNode)
					((JoinNode)fn).getPreNodes().add(this);
			}
		}
		super.load(e, FlowNodesMap);
	}
}
